<!--这是资料详情组件-->
<template>
  <div class="app-container">
    <el-form :model="postForm" v-loading="formLoading" :rules="rules" ref="postForm" label-width="220px"
             label-position="right">
     <p class="font-family-h font-bold margin-t50 margin-b40"><i class="square"></i>资料设置</p>
      <el-form-item label="资料名称：" prop="name">
        <el-input v-model="postForm.name" :maxlength=40  placeholder="请输入资料名称限40个字符以内" style="width: 650px"></el-input>
      </el-form-item>
      <el-form-item label="所属分类：" prop="datumCatId">
        <el-select v-model="postForm.datumCatId" placeholder="请选择分类" style="width: 508px">
          <el-option v-for="item in datumTypeOptions" :value="item.datumCatId" :label="item.name"
                     :key="item.datumCatId"></el-option>
        </el-select>
        <el-button type="primary" icon="el-icon-edit" @click="linkToCourseSort" style="width:140px;">添加分类</el-button>
      </el-form-item>
      <el-form-item label="下载权限：" prop="permission">
        <el-select v-model="postForm.permission" placeholder="请选择分类" style="width: 650px" @change="limitSelect">
          <el-option v-for="item in limitOptions" :value="item.key" :label="item.value" :key="item.key"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所需积分：" prop="price" v-if="isDatumPrice">
        <el-input type="number" v-model="postForm.price" placeholder="请输入价格" style="width: 650px"></el-input>
      </el-form-item>
      <el-form-item label="上传资料：" prop="datumList">
        <el-upload style="width: 650px"
                   class="upload-demo"
                   ref="upload"
                   action="https://upload-z2.qiniup.com"
                   :on-progress="uploadOnProgress"
                   :on-success="handleSuccess"
                   :on-change="onChange"
                   :on-preview="handlePreview"
                   :on-remove="handleRemove"
                   :on-error="handleError"
                   :limit="1"
                   :file-list="datumList"
                   :on-exceed="onExceed"
                   :before-upload="beforeUpload"
                   :data="formData"
                   :auto-upload="true"
                   accept=".doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf"
                   >
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
          <!--<el-button style="margin-left: 10px;" size="small" :disabled='this.postForm.qiniuObject!=null' type="success"-->
                     <!--v-loading="btnLoading" @click="submitUpload">{{btnText}}-->
          <!--</el-button>-->
        </el-upload>
      </el-form-item>
      <el-form-item label="资料排序：" prop="sort">
        <el-input min="0" type="number" v-model="postForm.sort" placeholder="请输入资料排序" style="width: 150px"></el-input>
        <span class="margin-l10 fc">默认为0排序大的排在前面</span>
      </el-form-item>
      <el-form-item label="下载次数：" prop="downloadTimes">
        <el-input type="number" v-model="postForm.downloadTimes" placeholder="请输入下载次数" style="width: 150px"></el-input>
        <span class="margin-l10 fc">默认为0用于前端展示</span>
      </el-form-item>
      <p class="font-family-h font-bold margin-t50 margin-b40"><i class="square"></i>分享设置</p>
     <!--<el-form-item label="分享公众号标题：" >-->
        <!--<el-input v-model="postForm.shareTitle" placeholder="请输入公众号标题" style="width: 650px"></el-input>-->
      <!--</el-form-item>-->
     <el-form-item label="分享公众号描述：" >
        <el-input :maxlength=29 v-model="postForm.shareDesc" placeholder="请输入描述,不超过29个字" style="width: 650px"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-check" v-loading="saveBtnLoading" @click="submitForm">保存</el-button>
        <el-button type="info" @click="close">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
  import { getUploadToken } from '@/api/qiniu'
  import { getAllDatumCat, saveDatum, getDatumDetail } from '@/api/datum'
  import { validateNumber } from '@/utils/vm'
  const postForm = {
    name: '',
    datumCatId: '',
    permission: '',
    price: null,
    sort: '',
    isUpload: 0,
    datumName: null,
    qiniuObject: null,
    format: null,
    datumSize: 0,
    downloadTimes: 0,
    datumId: null,
    shareTitle: null,
    shareDesc: null
  }
  const datumTypeOptions = [] // 资料分类
  const limitOptions = [
    { key: 17, value: 'vip免费' },
    // { key: 20, value: 'svip免费' },
    { key: 19, value: '免费' },
    { key: 18, value: '收费' }
  ]
  var validateUpload = (rule, value, callback) => {
    if (value === '' || value === null) {
      callback(new Error('请上传文件'))
    } else {
      callback()
    }
  }
  const rules = {
    name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
    datumCatId: [{ required: true, message: '请选择分类', trigger: 'change' }],
    price: [{ required: true, validator: validateNumber, trigger: 'blur' }],
    permission: [{ required: true, message: '请选择权限', trigger: 'change' }],
    datumList: [{ required: true, validator: validateUpload, trigger: 'submitForm' }],
    downloadTimes: [{ validator: validateNumber, trigger: 'blur' }],
    sort: [{ validator: validateNumber, trigger: 'blur' }]
  }
  export default {
    data() {
      return {
        btnText: '上传到服务器',
        name: 'second',
        postForm: Object.assign({}, postForm),
        rules,
        formData: {
          token: null
          // key: null
        },
        percent: 0,
        datumList: [],
        fileName: null,
        status: null,
        datumTypeOptions,
        limitOptions,
        formLoading: false,
        btnLoading: false,
        saveBtnLoading: false,
        isDatumPrice: false
      }
    },
    props: {
      isEdit: {
        type: Boolean,
        default: false
      }
    },
    created() {
      console.log(this.$route.params.datumId)
      this.postForm.datumId = this.$route.params.datumId
      if (this.postForm.datumId) {
        this.editDatum()
      }
      getAllDatumCat().then(res => {
        this.datumTypeOptions = res.data.data
      }).catch(er => {
        console.log(er)
      })
      this.getToken()
    },
    watch: {
      // 监听路由名称变化 重新调用数据
      $route: function(to, from) {
        console.log(to)
        if (to.name == 'editDatum') {
          this.postForm.datumId = this.$route.params.datumId
          this.datumList = []
          this.editDatum()
          this.datumList = this.datumList.slice(0, 1)
        }
      }
    },
    methods: {
      getToken() {
        getUploadToken().then(res => {
          if (res.data.statusCode == 200) {
            this.formData.token = res.data.data
          } else {
            this.$message({
              message: 'token获取失败，请稍后再试!',
              type: 'error'
            })
          }
        }).catch(err => {
          console.log(err)
        })
      },
      uploadOnProgress(event, file) {
        this.percent = (event.loaded / event.total * 100).toFixed(2)
        console.log('进度' + this.percent)
        this.status = '上传中'
      },
      onChange(file, filelist) {
        console.log('文件file: ' + JSON.stringify(file))
        this.fileName = file.name
        this.postForm.datumName = file.name
        this.postForm.datumSize = file.size
        const arrName = file.name.split('.')
        this.postForm.format = arrName[arrName.length - 1]
        console.log(this.postForm.format)
        // this.uploadShow = true
      },
      // onChange(info) {
      //   console.log(info)
      // },
      test() {
        console.log('test')
      },
      onExceed(files, fileList) {
        // // console.log(files)
        this.$message({
          message: '请先删除原来的资料!',
          type: 'error'
        })
        // console.log(fileList)
      },
      handleSuccess(response, file, fileList) {
        this.postForm.qiniuObject = response.key
        this.percent = 100
        this.status = '上传成功'
        this.postForm.isUpload = 1 // 上传成功标志
        this.fileName = file.name
        this.btnText = '点击上传服务器'
        this.btnLoading = false
      },
      stopUpload() {
        // this.$refs.upload.clearFiles()
      },
      handleError(error, response, file) {
        this.status = '上传失败'
        console.log(error.toString())
      },
      beforeUpload(file) {
        // this.formData.key = 'courses/' + this.courseId + '/' + file.name
        this.percent = 0
        this.status = '开始上传'
      },
      editDatum() {
        getDatumDetail(this.postForm.datumId).then(res => {
          console.log('资料明细' + JSON.stringify(res.data.data))
          this.postForm = res.data.data
          this.postForm.isUpload = 0
          if (this.postForm.permission != 19) {
            this.isDatumPrice = true
          } else {
            this.isDatumPrice = false
          }
          this.postForm.datumName = this.postForm.datumName ? this.postForm.datumName : this.postForm.name + '.' + this.postForm.format
          this.datumList.push({
            name: this.postForm.datumName,
            url: this.postForm.qiniuObject
          })
          console.log('文件个数' + JSON.stringify(this.datumList))
        }).catch(er => {
          console.log(er)
        })
      },
      limitSelect(val) {
        if (val != 19) {
          this.isDatumPrice = true
        } else {
          this.isDatumPrice = false
        }
      },
      linkToCourseSort() {
        this.$router.push({ name: `addDatumSort`, params: { isEdit: this.isEdit, datumId: this.$route.params.datumId }})
      },
      close() {
        this.$store.dispatch('delVisitedViews', this.$route).then((views) => {
          const latestView = views.slice(-1)[0]
          console.log(latestView)
          if (latestView) {
            const activeName = localStorage.getItem('datumBar')
            this.$router.push({ name: 'datums', params: { activeName: activeName }}) // latestView.path
          } else {
            this.$router.push('/')
          }
        })
      },
      submitForm() {
        this.postForm.fileName = this.fileName
        if (this.postForm.name == '' || this.postForm.name == null) {
          this.$message({ message: '资料名称必填' })
          return
        }
        if (this.postForm.datumCatId == '' || this.postForm.datumCatId == null) {
          this.$message({ message: '资料分类必选' })
          return
        }
        if (this.postForm.permission == '' || this.postForm.permission == null) {
          this.$message({ message: '资料权限必选' })
          return
        }
        if (this.postForm.permission != 19) {
          if (this.postForm.price == '' || this.postForm.price == null || this.postForm.price <= 0) {
            this.$message({ message: '价格必填且要大于0' })
            return
          }
        }
        if (this.postForm.qiniuObject == '' || this.postForm.qiniuObject == null) {
          this.$message({ message: '文件必传' })
          return
        }
        console.log(this.postForm)
        this.$refs.postForm.validate(valid => {
          if (valid) {
            if (this.saveBtnLoading) {
              return
            }
            this.saveBtnLoading = true
            this.formLoading = true
            console.log('提交资料' + JSON.stringify(this.postForm))
            saveDatum(this.postForm).then(res => {
              this.formLoading = false
              this.saveBtnLoading = false
              console.log(res.data)
              this.$message({
                type: 'success',
                message: res.data.data.msg
              })
              this.close()
            }).catch(err => {
              this.formLoading = false
              this.saveBtnLoading = false
              console.log(err)
            })
          } else {
            this.$message({
              type: 'info',
              message: '请将必填项填写完！'
            })
          }
        })
      },
      submitUpload() {
        if (this.fileName == null) {
          this.$message({
            message: '请选择要上传的资料文件',
            type: 'warning'
          })
          return false
        }
        this.btnText = '上传中'
        this.btnLoading = true
        this.$refs.upload.submit()
      },
      handleRemove(file, fileList) {
        console.log(file, fileList)
        this.fileName = null
        this.postForm.qiniuObject = null
        this.btnLoading = false
        this.btnText = '上传到服务器'
      },
      handlePreview(file) {
        console.log(file)
      }
    }
  }
</script>
<style scoped>

</style>
